use std::time::Duration;
use tokio::time::{interval, Instant};
use uuid::Uuid;
use tracing::{info, error, warn, debug};

use crate::config::{ConfigManager, DeviceConfig, PointConfig};
use crate::modbus::ModbusClientManager;
use crate::storage::DataStorage;
use crate::error::{Result, ModbusCollectorError};

/// 采集任务
#[derive(Debug, Clone)]
pub struct CollectionTask {
    pub task_id: String,
    pub device_id: String,
    pub device_config: DeviceConfig,
    pub points: Vec<PointConfig>,
    pub interval_ms: u64,
    pub last_execution: Option<Instant>,
    pub enabled: bool,
}

impl CollectionTask {
    pub fn new(device_config: DeviceConfig, points: Vec<PointConfig>) -> Self {
        Self {
            task_id: Uuid::new_v4().to_string(),
            device_id: device_config.device_id.clone(),
            interval_ms: device_config.interval,
            device_config,
            points,
            last_execution: None,
            enabled: true,
        }
    }
    
    /// 检查是否需要执行
    pub fn should_execute(&self, now: Instant) -> bool {
        if !self.enabled {
            return false;
        }
        
        match self.last_execution {
            None => true,
            Some(last) => {
                let elapsed = now.duration_since(last);
                elapsed >= Duration::from_millis(self.interval_ms)
            }
        }
    }
    
    /// 更新执行时间
    pub fn update_execution_time(&mut self, time: Instant) {
        self.last_execution = Some(time);
    }
}